package org.simplecrm.controllers.events;

import org.simplecrm.controllers.events.propertyeditors.CustomerPropertyEditor;
import org.simplecrm.controllers.events.propertyeditors.EventTypePropertyEditor;
import org.simplecrm.controllers.events.propertyeditors.SupportPropertyEditor;
import org.simplecrm.domain.customer.Customer;
import org.simplecrm.domain.event.Event;
import org.simplecrm.domain.event.eventtype.EventType;
import org.simplecrm.domain.user.User;
import org.simplecrm.service.customer.CustomerService;
import org.simplecrm.service.event.EventService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.validation.Valid;
import java.util.List;

import static org.simplecrm.controllers.CrmUrls.*;

/**
 * Created by Oleksandr_Terekh on 9/16/2014.
 */
@Controller
@RequestMapping("/crm/events")
public class EventController {

    private static final int EVENTS_PAGE_SIZE = 3;

    @org.simplecrm.misc.loginject.Logger
    private Logger LOGGER;

    @Autowired
    private CustomerService customerService;

    @Autowired
    private EventService eventService;

    @InitBinder
    public void initBinderAll(WebDataBinder binder) {
        binder.registerCustomEditor(EventType.class, new EventTypePropertyEditor());
        binder.registerCustomEditor(User.class, new SupportPropertyEditor());
        binder.registerCustomEditor(Customer.class, new CustomerPropertyEditor());
    }

    @RequestMapping("/view/{customerId}/{pageNum}")
    public ModelAndView viewEventsOfCustomerByPage(@PathVariable("customerId") Integer customerId,
                                                   @PathVariable("pageNum") Integer pageNum) {

        List<Event> eventsPage = eventService.getEventsPage(customerId, pageNum, EVENTS_PAGE_SIZE);

        ModelAndView modelAndView = new ModelAndView(URL_VIEWEVENTS_PAGE);
        modelAndView.getModelMap().addAttribute("customerEvents", eventsPage);
        modelAndView.getModelMap().addAttribute("customerId", customerId);
        modelAndView.getModelMap().addAttribute("lastPage", pageNum * EVENTS_PAGE_SIZE >= eventService.getEventsCount(customerId));
        modelAndView.getModelMap().addAttribute("currentPage", pageNum);
        return modelAndView;
    }

    @RequestMapping("/new")
    public String newEvent(@Valid @ModelAttribute("event") Event event,
                           final BindingResult bindingResult,
                           final RedirectAttributes redirectAttributes) {

        if (bindingResult.hasErrors()) {

            redirectAttributes.addFlashAttribute("org.springframework.validation.BindingResult.event", bindingResult);
            redirectAttributes.addFlashAttribute("event", event);
            LOGGER.debug("Add event failed: " + event);
        } else {

            eventService.addNewEvent(event);
            redirectAttributes.addFlashAttribute("done", true);
            LOGGER.debug("Added event: " + event);
        }

        return URL_REDIRECT_CUSTOMERS + "/1";
    }

    @RequestMapping("/update/prepare/{customerId}/{eventId}")
    public ModelAndView prepareUpdate(@PathVariable("customerId") Integer customerId,
                                      @PathVariable("eventId") Integer eventId) {

        ModelAndView modelAndView = new ModelAndView(URL_EDITEVENT_PAGE);

        Event event = eventService.getEventById(eventId);
        event.setCustomer(customerService.getCustomerById(customerId));
        modelAndView.getModelMap().addAttribute("eventToUpdate", event);

        return modelAndView;
    }

    @RequestMapping("/update")
    public String updateEvent(@Valid @ModelAttribute("eventToUpdate") Event event,
                              final BindingResult bindingResult,
                              RedirectAttributes redirectAttributes) {

        if (bindingResult.hasErrors()) {

            LOGGER.debug("Update event failed: " + event);
            return URL_EDITEVENT_PAGE;
        } else {

            eventService.updateEvent(event);
            redirectAttributes.addFlashAttribute("done", true);
            LOGGER.debug("Updated event: " + event);
        }

        return URL_REDIRECT_CUSTOMERS + "/1";
    }

    @RequestMapping("/delete/{eventId}")
    public String deleteEvent(@PathVariable("eventId") Integer eventId,
                              RedirectAttributes redirectAttributes) {

        eventService.deleteEvent(eventId);
        redirectAttributes.addFlashAttribute("done", true);
        return URL_REDIRECT_CUSTOMERS + "/1";
    }
}
